﻿/*
Copyright 2002-2011 Corey Trager
Distributed under the terms of the GNU General Public License
*/

using OpenPop.Pop3;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace btnet
{
    public class EngineMail
    {

        static int MAX_EMAILS_PER_TIME = 10;

        private bool CheckStartString(string s, string[] arrTemplate)
        {
            s = s.ToLower();
            for (int i = 0; i < arrTemplate.Length; i++)
                if (s.StartsWith(arrTemplate[i])) return true;
            return false;
        }

        private string ExtractNewBody(string sBody)
        {
            string[] sSpecialStringArr = new string[4];
            sSpecialStringArr[0] = "from:";
            sSpecialStringArr[1] = "to:";
            sSpecialStringArr[2] = "sent:";
            sSpecialStringArr[3] = "subject:";
            int nCounter = 0,maxIndex;

            string[] sLineArr = sBody.Split(new char[] { '\n' });
            for (int i = 0; i < sLineArr.Length; i++)
            {
                maxIndex = i + sSpecialStringArr.Length;
                if (maxIndex >= sLineArr.Length) maxIndex = sLineArr.Length - 1;
                nCounter = 0;
                for (int nElement = i; nElement <= maxIndex; nElement++)
                {
                    if (CheckStartString(sLineArr[nElement], sSpecialStringArr)) nCounter++;
                    else break;
                }
                if (nCounter >= 2)
                {
                    //Da tim thay
                    sBody = "";
                    for (int nResult = 0; nResult < i; nResult++)
                    {
                        sBody = sBody + sLineArr[nResult] + "\n";
                    }
                    return sBody;
                }
            }
            return sBody;
        }

        public List<BugMail> GetMail()
        {
            List<BugMail> arrRequestCommand = new List<BugMail>();
            string sModuleId = "", sCMD = "", sNote = "", sATMNo = "", sUsername = "", sPassword = "", sMatchAlarmId = "";
            int nNumberItems;
            string[] LineArr;
            string sBody;
            int counter = 0;
            string sEmailAddress = "";

            try
            {
                Pop3Client emailClient = new Pop3Client();

                //emailClient.Connect(ART.Windows.HelpDesk.TicketServerCore.Variables.POPSERVER,
                //    Convert.ToInt32(ART.Windows.HelpDesk.TicketServerCore.Variables.POPPORT), ART.Windows.HelpDesk.TicketServerCore.Variables.POPSSL);
                //emailClient.Authenticate(ART.Windows.HelpDesk.TicketServerCore.Variables.POPUSERNAME,
                //    ART.Windows.HelpDesk.TicketServerCore.Variables.POPPASSWORD);

                emailClient.Connect("mail.anlocjsc.vn", 110, false);
                emailClient.Authenticate("support@anlocjsc.vn", "lvc@@anl0c@@hn123");

                //emailClient.Connect("pop.gmail.com", 995, true); // enable SSL
                //emailClient.Authenticate("mr.qlot", "10011990");

                int MsgCount = emailClient.GetMessageCount();

                for (int iMessage = MsgCount; iMessage >= 1; iMessage--)
                {
                    try
                    {
                        counter++;
                        if (counter > MAX_EMAILS_PER_TIME) break;

                        sModuleId = "";
                        sCMD = "";
                        sNote = "";
                        sATMNo = "";
                        sBody = "";

                        OpenPop.Mime.Message myMessage = emailClient.GetMessage(iMessage);
                        if (myMessage.Headers.Subject.Replace(" ", "").Contains(btnet.Util.
                            get_setting("TrackingIdString", "DO NOT EDIT THIS:").Replace(" ", "")))
                        {
                            sEmailAddress = myMessage.Headers.From.MailAddress.Address;
                            string sEmailHead = myMessage.Headers.Subject;
                            if (myMessage.MessagePart.IsMultiPart)
                            {
                                for (int iPart = 0; iPart < myMessage.MessagePart.MessageParts.Count; iPart++)
                                {
                                    if (myMessage.MessagePart.MessageParts[iPart].IsText)
                                    {
                                        sBody = myMessage.MessagePart.MessageParts[iPart].GetBodyAsText();
                                        break;
                                    }
                                }
                            }
                            else
                                sBody = myMessage.MessagePart.GetBodyAsText();


                            sBody = ExtractNewBody(sBody);

                            arrRequestCommand.Add(new BugMail(sEmailAddress, sEmailHead, sBody));
                            //Parsing mail
                            //…

                            emailClient.DeleteMessage(iMessage); //Nếu cần xoá message

                            //Xử lý nếu đủ thông tin
                            //…
                        }
                    }
                    catch (Exception ex2)
                    {
                        //if (!m_objStopEvent.WaitOne(0, true)) PECaches.GetErrorQueue().Enqueue(new PEError("AlarmEmailCore.POPMail", "GetMessage", ex2));                        
                    }
                }
                emailClient.Disconnect();
            }
            catch (Exception ex)
            {
                //if (!m_objStopEvent.WaitOne(0, true)) PECaches.GetErrorQueue().Enqueue(new PEError("AlarmEmailCore.POPMail", "GetMessage", ex));
            }

            return arrRequestCommand;
        }

        public void ProcessMails()
        {
            string sql = @"declare @now datetime
		        begin
			        -- signal that we DID do the update
			        set @now = getdate()

			        update bugs set
			        bg_last_updated_user = $lu,
			        bg_last_updated_date = @now
			        where bg_id = $id
		        end
		        select @now";

            var tmpData = GetMail();
            foreach (BugMail content in tmpData)
            {
                var dataUser = btnet.User.get_user_by_email(content.SendAddr);
                var objUser = dataUser.Tables[0].Rows[0];

                var security = new Security();
                security.user.usid = Convert.ToInt32(objUser["us_id"]);

                string strTmp = content.HeadMail.Replace(" ", "");
                strTmp = strTmp.Substring(strTmp.
                    IndexOf(btnet.Util.get_setting("TrackingIdString", "DO NOT EDIT THIS:").Replace(" ", "")) +
                    btnet.Util.get_setting("TrackingIdString", "DO NOT EDIT THIS:").Replace(" ", "").Length);
                strTmp = strTmp.Substring(0, strTmp.IndexOf(")"));
                var bugId = Convert.ToInt32(strTmp);

                sql = sql.Replace("$lu", Convert.ToString(security.user.usid));
                sql = sql.Replace("$id", Convert.ToString(bugId));

                DateTime last_update_date = (DateTime)btnet.DbUtil.execute_scalar(sql);

                string comment_formated = content.BodyMail;
                string comment_search = content.BodyMail;
                string commentType = "text/plain";
                bool internal_only = false;

                bool bugpost_fields_have_changed = (btnet.Bug.insert_comment(
                    bugId,
                    security.user.usid,
                    comment_formated,
                    comment_search,
                    null, // from
                    null, // cc
                    commentType,
                    internal_only) != 0);


                if (bugpost_fields_have_changed && !internal_only)
                {
                    bool status_changed = false;
                    bool assigned_to_changed = false;
                    int assignedId = 0;

                    btnet.Bug.send_notifications(btnet.Bug.UPDATE, bugId, security, 0,
                        status_changed,
                        assigned_to_changed,
                        assignedId);

                }

            }
        }


    }


    public class BugMail 
    {
        public string SendAddr;
        public string HeadMail;
        public string BodyMail;

        public BugMail(string _SendAddr, string _HeadMail, string _BodyMail)
        {
            SendAddr = _SendAddr;
            HeadMail = _HeadMail;
            BodyMail = _BodyMail;
        }

    }

} // end namespace